package org.ellisande.grid.tags;

import java.util.EnumSet;

import javax.servlet.jsp.JspWriter;

import org.ellisande.grid.tags.support.TagBuilder;
import org.ellisande.tld.annotations.Attribute;
import org.ellisande.tld.annotations.Description;
import org.ellisande.tld.annotations.Info;
import org.ellisande.tld.annotations.Tag;

@Tag
@Info("Creates a progress bar with the defined type and percentage complete.")
public class ProgressBarTag extends AbstractTag {

	private static final long serialVersionUID = -457186555883116226L;

	protected static enum Type {
		PRIMARY("progress-primary"), INFO("progress-info"), SUCCESS("progress-success"), WARNING("progress-warning"), DANGER("progress-danger");

		private String type;

		private Type(String type) {
			this.type = type;
		}

		public String toString() {
			return type;
		}
	}
	
	@Attribute
	@Description("Defines the type of the progress bar. Allowed values: primary | info | success | warning | danger. Default value: primary")
	private Type type = Type.PRIMARY;
	
	@Attribute
	@Description("Defines the percentage of the progress bar that should be filled. Allowed values: 0 - 100. Default value: 50.")
	private int fillAmount = 50;
	
	public void setType(String type){
		for(Type current : EnumSet.allOf(Type.class)){
			if(current.name().equalsIgnoreCase(type)){
				this.type = current;
				return;
			}
		}
	}
	
	public void setFillAmount(String amount){
		int fillAmount = 0;
		try {
			fillAmount = Integer.valueOf(amount);
		} catch (NumberFormatException e) {
			return;
		}
		
		if(fillAmount < 0 || fillAmount > 100) return;
		
		this.fillAmount = fillAmount;
	}

	@Override
	public void startTag() throws Exception {
		TagBuilder progress = createTagBuilder("div");
		TagBuilder bar = createTagBuilder("div");
		progress.addStyle("progress");
		progress.addStyle(type.toString());
		
		bar.addStyle("bar");
		bar.addAttribute("style", "width: "+fillAmount+"%;");
		
		JspWriter out = pageContext.getOut();
		out.write(progress.compileStartTag());
		out.write(bar.compileStartTag());
	}

	@Override
	public void endTag() throws Exception {
		JspWriter out = pageContext.getOut();
		out.write("</div>");
		out.write("</div>");
	}

}
